﻿export async function sysLoad() {
    return await new Promise(function (resolve, reject) {
        //fetch('/sys/load', { credentials: 'same-origin' })
            fetch('http://localhost:8080/sys/load')
            .then(res => res.json())
            .then(data => resolve(data));
    })
    //{user:{eno,name,isApprover},modules:[true,true/false,true,true],collegeName,permissions}
}

export async function loadSendState() {
    return await new Promise(function (resolve, reject) {
        //fetch('/send/load', { credentials: 'same-origin' })
            fetch('http://localhost:8080/send/load')
            .then(res => res.json())
            .then(deps => {
                if (!deps) console.log('failed to load sending staff tree!');
                resolve(deps)
            })
    })
}

export async function loadAuthorizeState() {
    return await new Promise(function (resolve, reject) {
        //fetch('/authorize/load', { credentials: 'same-origin' })
          fetch('http://localhost:8080/authorize/load')
            .then(res => res.json())
            .then(deps => {
                if (!deps) console.log('failed to load authorize staff tree!');
                resolve(deps)
            })
    })
}

export async function submitPerm(teacher) {
    await fetch(`http://localhost:8080/authorize/update/${teacher.eno}/${teacher.perm}`, { method: 'POST' })
    /*await fetch(`/authorize/update/${teacher.eno}/${teacher.perm}`, {
        method: 'POST',
        credentials: 'same-origin'
    });*/
}

export async function sendSms(msg, receivers) {
    // receivers: [{id,type},...]
    var txt = await new Promise(function (resolve, reject) {
        fetch('/send', {
            credentials: 'same-origin',
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json;charset=utf-8'
            },
            body: JSON.stringify({ msg, receivers })
        }).then(res => res.text())
            .then(echo => resolve(echo))
    });
    return txt;
}

export async function loadStatisticState() {
    return await loadJson('http://localhost:8080/stat/load');
    
    //return await loadJson('/stat/load');
}

export async function loadHistoryState() {
    return await loadJson('http://localhost:8080/history');

    //return await loadJson('/history');
}

export async function loadHistoryPage(category, page) {
    return await loadJson(`http://localhost:8080/history/${category}/${page}`);
    //return await loadJson(`/history/${category}/${page}`);
}

export async function parseStaff(file) {
    return await test();
}
export async function uploadStaff(org) {

}

function loadJson(url) { return fetch(url, { credentials: 'same-origin' }).then(res => res.json()) }